﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;
using System.Xml.Linq;
using Netkk.Common;
using Netkk.Common.Interfaces.Repositories;
using Netkk.Common.Models;

namespace Netkk.Data.Repositories
{
    public class LinkRepository : BaseRepository, ILinkRepository
    {
        private string linkPath;

        protected XDocument LinkDocument
        {
            get { return CacheWrapper.Load("links", new CacheDependency(linkPath), () => XDocument.Load(linkPath)); }
        }

        public LinkRepository()
        {
            linkPath = string.Concat(ConnectionString, "Links.xml");
        }

        public IEnumerable<Link> Select()
        {
            IEnumerable<Link> links = from l in LinkDocument.Element("Links").Elements("Link")
                                      select getLinkFromXElement(l);
            return links;
        }

        private Link getLinkFromXElement(XElement XLink)
        {
            return new Link
            {
                Id = XLink.Element("Id").Value.ToOrDefault<Guid>(),
                Name = XLink.Element("Name").Value,
                Url = XLink.Element("Url").Value,
                Description = XLink.Element("Description").Value,
                Order = XLink.Element("Order").Value.ToOrDefault<int>(),
                Category = XLink.Element("Category").Value,
            };
        }

        public void Save(Link link)
        {
            XElement xlink = (from l in LinkDocument.Element("Links").Elements("Link")
                              where l.Element("Id").Value.ToOrDefault<Guid>() == link.Id
                              select l).FirstOrDefault();
            if (xlink == null)
            {
                xlink = new XElement("Link");
                LinkDocument.Element("Links").Add(xlink);
            }
            else
            {
                xlink.RemoveAll();
            }

            xlink.Add(
                new XElement("Id") { Value = link.Id.ToString("B") },
                new XElement("Name") { Value = link.Name },
                new XElement("Url") { Value = link.Url },
                new XElement("Description") { Value = link.Description },
                new XElement("Order") { Value = link.Order.ToString() },
                new XElement("Category") { Value = link.Category });

            LinkDocument.Save(linkPath);
        }

        public void Delete(Link link)
        {
            XElement xlink = (from l in LinkDocument.Element("Links").Elements("Link")
                              where l.Element("Id").Value.ToOrDefault<Guid>() == link.Id
                              select l).FirstOrDefault();
            if (xlink != null)
            {
                xlink.Remove();
                LinkDocument.Save(linkPath);
            }
        }

    }

}
